package org.example.sdk;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class ResourceController {

    @Autowired
    private ResourceService resourceService;

    @Autowired
    private NextTokenEncoderManager nextTokenEncoderManager;

    @GetMapping("/{resource}")
    public FindResult<?> find(
            @PathVariable(name = "resource") String resource,
            @RequestParam(name = "limit", required = false) Integer limit,
            @RequestParam(name = "next_token", required = false) String nextTokenStr
    ) {
        NextTokenEncoder nextTokenEncoder = nextTokenEncoderManager.getNextTokenEncoder(resource);
        Object nextToken = nextTokenEncoder.decode(nextTokenStr);
        Query query = Query.builder()
                .limit(limit)
                .nextToken(nextToken)
                .build();
        FindResult<?> result = resourceService.find(resource, query);
        result.setNextToken(nextTokenEncoder.encode(result.getNextToken()));
        return result;
    }

}
